import { useUserStore } from '@/stores/user'

// 基础配置
const BASE_URL = 'https://www.pengfei.site'
const TIMEOUT = 10000

// 请求方法封装
const request = {
    // GET请求
    get: (url, params = {}) => {
        return requestMethod('GET', url, null, params)
    },

    // POST请求
    post: (url, data = {}) => {
        return requestMethod('POST', url, data)
    },

    // PUT请求
    put: (url, data = {}) => {
        return requestMethod('PUT', url, data)
    },

    //patch请求
    patch: (url, data = {}) => {
        return requestMethod('PATCH', url, data)
    },

    // DELETE请求
    delete: (url, params = {}) => {
        return requestMethod('DELETE', url, null, params)
    }
}

// 统一的请求方法
const requestMethod = (method, url, data = null, params = {}) => {
    return new Promise((resolve, reject) => {
        // 从store中获取token
        const userStore = useUserStore()
        const token = userStore.accessToken

        // 构建完整URL
        let fullUrl = BASE_URL + url

        // 处理GET请求的查询参数
        if (method === 'GET' && Object.keys(params).length > 0) {
            const queryString = Object.keys(params)
                .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
                .join('&')
            fullUrl += `?${queryString}`
        }

        // 构建请求头
        const headers = {
            'Content-Type': 'application/json'
        }

        if (token) {
            headers.Authorization = `Bearer ${token}`
        }

        // 构建请求配置
        const requestConfig = {
            url: fullUrl,
            method: method,
            timeout: TIMEOUT,
            header: headers,
            success: (res) => {
                console.log('响应数据:', res.data)

                // 处理HTTP状态码
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else {
                    // 处理错误状态码
                    const error = {
                        statusCode: res.statusCode,
                        data: res.data,
                        message: res.data?.message || `请求失败，状态码: ${res.statusCode}`
                    }

                    // 处理401未授权错误
                    if (res.statusCode === 401) {
                        userStore.logout()
                        uni.navigateTo({
                            url: '/pages/login/login'
                        })
                    }

                    reject(error)
                }
            },
            fail: (err) => {
                console.error('请求失败:', err)
                const error = {
                    message: err.errMsg || '网络请求失败',
                    err: err
                }
                reject(error)
            }
        }

        // 添加请求体数据
        if (data && (method === 'POST' || method === 'PUT')) {
            requestConfig.data = data
        }

        console.log('请求配置:', requestConfig)

        // 发送请求
        uni.request(requestConfig)
    })
}

export default request
